<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购订单 / 订单维护 / 订单变更</span>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="margin-top: 20px">
      <el-form-item label="变更方" prop="identity">
        <el-input
            v-model="queryParams.identity"
            placeholder="请输入变更方"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变更人" prop="changePerson">
        <el-input
            v-model="queryParams.changePerson"
            placeholder="请输入变更人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变更状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择变更状态" clearable>
          <el-option
              v-for="dict in order_change_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增变更</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >批量删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="变更人" align="center" prop="changePerson" />
      <el-table-column label="变更时间" align="center" prop="changeTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.changeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变更方" align="center" prop="identity" />
      <el-table-column label="变更状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getTagStatus(scope.row.status)" disable-transitions>
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="变更详情" align="left" prop="type" width="450" header-align="center">
        <template #default="scope">
          <el-scrollbar max-height="80px">
            <div v-for="(activity, activityIndex) in scope.row.changeDetail" :key="activityIndex">
              <p style="display: inline-block;white-space: nowrap" ><strong>{{ activity.field }}：</strong></p>
              <p v-html="highlightText(activity.detail)" style="display: inline-block;white-space: nowrap"></p>
            </div>
          </el-scrollbar>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="success" icon="CircleCheck" @click="handlePass(scope.row)"
                     v-if="scope.row.status === '待审核' && scope.row.identity === '供货商'">通过</el-button>
          <el-button link type="danger" icon="CircleClose" @click="handleReject(scope.row)"
                     v-if="scope.row.status === '待审核' && scope.row.identity === '供货商'">驳回</el-button>
          <el-button link type="primary" icon="RefreshLeft" @click="handleDelete(scope.row,'撤回')"
                     v-if="scope.row.status === '待审核' && scope.row.identity === '运营商'">撤回</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row,'删除')"
                     v-if="scope.row.status !== '待审核'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 订单变更对话框 -->
    <el-dialog title="添加变更" v-model="open" width="600px" append-to-body>
      <el-form ref="changeDetailRef" :model="orderInfo" :rules="rules" label-width="110px" label-position="top" style="padding-right: 10px">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="采购订单编号" prop="orderNo">
              <el-input v-model="orderInfo.orderNo" disabled/>
            </el-form-item>
            <el-form-item label="采购负责人" prop="responsiblePerson">
              <el-input v-model="orderInfo.responsiblePerson" placeholder="请输入采购负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货地点" prop="deliveryAddress">
              <el-select v-model="orderInfo.deliveryAddress" placeholder="请选择交货地点" style="width: 100%" @change="handleSelectedAddressChange">
                <el-option
                    v-for="item in addressList"
                    :key="item.code"
                    :label="formatAddress(item)"
                    :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="orderInfo.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="orderInfo.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <el-divider content-position="center">订单详情信息</el-divider>

      <el-table :data="orderDetailList" style="margin-top: 15px">
        <el-table-column label="货品批号" align="center" prop="rawProductBatch" width="135"/>
        <el-table-column label="货品名称" align="center" prop="rawProductName" width="125"/>
        <el-table-column label="订购数量" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity"
                             :precision="2" controls-position="right" style="width: 90%"/>
          </template>
        </el-table-column>
        <el-table-column label="预期到货时间" align="center">
          <template #default="scope">
            <el-date-picker
                v-model="scope.row.expectedDeliveryTime"
                placeholder="请选择时间"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                style="width: 90%;"
            />
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Detail">
import {listDetail, addDetail, updateDetail, delDetailList, passChange} from "@/api/purchase/changeDetail.js";
import { parseTime } from "@/utils/ruoyi.js";
import { getChangeOrderDetail } from "@/api/purchase/orderDetail.js";
import {changePurchaseOrder, getPurchaseOrder} from "@/api/purchase/purchaseOrder.js";
import AMapLoader from "@amap/amap-jsapi-loader";
import {listDictDataAll} from "@/api/purchase/DictData.js";

const { proxy } = getCurrentInstance();
const { order_change_status } = proxy.useDict('order_change_status');

const detailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const orderNo = ref("");
const orderInfo = ref({});
const orderDetailList = ref([]);
const addressList = ref([]); // 交货地点列表

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    changePerson: null,
    identity: null,
    status: null
  },
  rules: {
    responsiblePerson: [
      { required: true, message: "负责人不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    deliveryAddress: [
      { required: true, message: "交货地点不能为空", trigger: "blur" }
    ],
    expectedDeliveryTime: [
      { required: true, message: "预期交货时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function initial(){
  if(proxy.$route.query.orderNo){
    orderNo.value = proxy.$route.query.orderNo;
    queryParams.value.orderNo = orderNo.value;
    getChangeOrderDetail(orderNo.value).then(response => {
      orderDetailList.value = response.rows;
    })
    getPurchaseOrder(orderNo.value).then(response => {
      orderInfo.value = response.data;
    });
    getList();
  }
}

/** 查询detail列表 */
function getList() {
  loading.value = true;
  listDetail(queryParams.value).then(response => {
    detailList.value = response.rows;
    for(let i = 0; i < detailList.value.length; i++){
      detailList.value[i].changeDetail =
          JSON.parse(detailList.value[i].changeDetail);
    }
    total.value = response.total;
    loading.value = false;
  });

  //获取地址信息
  const query = {type: '收货地址'}
  listDictDataAll(query).then(response => {
    addressList.value = response.data;
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.orderNo = orderNo.value;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  for(let i = 0; i < detailList.value.length; i++){
    if(detailList.value[i].status === '待审核'){
      proxy.$modal.msgError("存在未审核的订单详情，请先等待审核");
      return;
    }
  }
  initial();
  open.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["changeDetailRef"].validate(valid => {
    if (valid) {
      orderInfo.value.details = orderDetailList.value;
      changePurchaseOrder(orderInfo.value).then(response => {
        proxy.$modal.msgSuccess("订单变更成功");
        open.value = false;
        initial();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row,info) {
  const _ids = row.id || ids.value;
  if(info === undefined){
    info = "批量删除";
  }
  proxy.$modal.confirm('是否确认'+info+'变更信息？').then(function() {
    return delDetailList(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(info + "成功");
  }).catch(() => {});
}

function highlightText(input) {
  return input.replace(/\b(\S+?)\b/g, match => {
    if (match === "修改为") {
      return match;
    }
    return `<span style="color: rebeccapurple; font-weight: bold;">${match}</span>`;
  });
}

function handlePass(row){
  let change = {id:row.id, status:"已通过"}
  updateDetail(change).then(response => {
    passChange(row.id).then(response => {
      proxy.$modal.msgSuccess("更新成功");
      initial();
    });
  });
}

function handleReject(row){
  let change = {id:row.id, status:"已驳回"}
  updateDetail(change).then(response => {
    proxy.$modal.msgSuccess("更新成功");
    initial();
  });
}

function getTagStatus(status){
  if(status === '已通过'){
    return 'success';
  }
  if(status === '已驳回'){
    return 'danger';
  }
  return 'info';
}

/** 格式化订单交货地点的选择 */
function formatAddress(item) {
  return item.name + " - " + item.person + " - " + item.contact;
}

/** 选择交货地点后为负责人和联系电话赋值 */
function handleSelectedAddressChange(value){
  if(value){
    addressList.value.forEach(item => {
      if(item.name === value){
        orderInfo.value.responsiblePerson = item.person;
        orderInfo.value.contactPhone = item.contact;
        orderInfo.value.destinationLng = item.lng;
        orderInfo.value.destinationLat = item.lat;
      }
    })
  }
}

initial()
</script>